//loaded = false;
//
//function isLoaded() {
//    loaded = true;
//}
//
//window.onload = isLoaded();

function updateDateTextbox(txtboxId, dateArray) {

    var date = dateArray[0];
    var year = date[0];
    var month = date[1];
    var day = date[2];
    var formattedDate = date + '-' + convertMonth(month) + '-' + year;

    var txtBox = document.getElementById(txtBoxId);
    txtBox.value = formattedDate;

}
//function handleDateSelect(type, args, obj) {
//    var dates=args[0];
//    var date=dates[0];
//    var year=date[0];
//    var month=date[1];
//    var day = date[2];
//
//    $('turninDate').value= day + "/" + month + "/" + year;
//
//    updateDrmoTurninDate();
//}
//
//YAHOO.drmoPackage.cal1.selectEvent.subscribe(handleDateSelect, YAHOO.drmoPackage.calendar.cal1, true);

function updateDrmoTurninDate() {

    var txtDate = ('turninDate').value;

    if (txtDate != '') {
        YAHOO.createDrmoPackage.myCal.select(txtDate.value);
        var selectedDates = YAHOO.createDrmoPackage.myCal.getSelectedDates();
        var date = selectedDates[0];
        //YAHOO.createDrmoPackage.myCal.cfg.setProperty("pageDate", (date.getMonth()+1) + "/" + date.getYear());
        //YAHOO.createDrmoPackage.myCal.render();

        //var date = dateArray[0];
        var year = date[0];
        var month = date[1];
        var day = date[2];
        var formattedDate = date + '-' + convertMonth(month) + '-' + year;

        var txtBox = document.getElementById(txtBoxId);
        txtBox.value = formattedDate;
    }
}

function convertMonth(month) {

    switch (month) {
        case 1:
            return 'JAN';
        case 2:
            return 'FEB';
        case 3:
            return 'MAR';
        case 4:
            return 'APR';
        case 5:
            return 'MAY';
        case 6:
            return 'JUN';
        case 7:
            return 'JUL';
        case 8:
            return 'AUG';
        case 9:
            return 'SEP';
        case 10:
            return 'OCT';
        case 11:
            return 'NOV';
        case 12:
            return 'DEC';
    }

    return null;
}

function confirmRemoveAlternateCustodian(custodianId) {

    if (confirm("Are you sure you wish to delete this account custodian?")) {
        window.parent.location = "adpeAccountAction.do?method=removeAlternateCustodian&userId=" + custodianId;
    }
}

function confirmDeleteDrmoPackage(id, dtid) {
    if (confirm("Are you sure you wish to delete package " + dtid + "?")) {
        window.parent.location = "drmo/deletePackage.do?id=" + id;
    }
}

function confirmCloseDrmoPackage(id, dtid) {
    if (confirm("Are you sure you wish to complete package " + dtid + "? (You will no longer be able to edit the package)")) {
        window.parent.location = "drmo/closePackage.do?drmoPackageId=" + id;
    }
}

function confirmDeleteRosPackage(id, packageName) {

    if (confirm("Are you sure you want to delete ROS package " + packageName + "?")) {
        window.parent.location = "ros/deletePackage.do?rosPackageId=" + id;
    }

}

function confirmCloseRosPackage(id, packageName) {
    if (confirm("Are you sure you want to close ROS package " + packageName + "? (YOU WILL NO LONGER BE ABLE TO ADD ITEMS!)")) {
        window.parent.location = "ros/closePackage.do?rosPackageId=" + id;
    }
}
function confirmOutprocessUser(id, displayName) {
    if (confirm("Are you sure you wish to outprocess user " + displayName + "? YOU WILL NOT BE ABLE TO UNDO THIS ACTION!")) {
        window.parent.location = "user/outprocess.do?userId=" + id;
    }
}

function createNewMultipleItemsRow() {

    if (isLoaded()) {
        var table = document.getElementById('equipmentItemTable');
        var newRow = table.tBodies[0].rows[1].cloneNode(true);
        var selectBoxes = newRow.getElementsByTagName('select');
        for (var i = 0; i < selectBoxes.length; i++) {
            selectBoxes[i].value = -1;
        }
        var textBoxes = newRow.getElementsByTagName('input');
        for (var i = 0; i < textBoxes.length; i++) {
            textBoxes[i].value = '';
        }
        table.tBodies[0].appendChild(newRow);
    }


}
/* AJAX FUNCTIONALITY */

function createModelFakeSubmit() {

    var manufacturerId = document.getElementById("manufacturerId").value;
    var equipmentTypeId = document.getElementById('equipmentTypeId').value;
    var modelName = document.getElementById('modelName').value;
    var processorSpeed = document.getElementById('processorSpeed').value;
    var screenSize = document.getElementById('screenSize').value;

    var postString = "manufacturerId=" + manufacturerId + "&equipmentTypeId=" + equipmentTypeId + "&modelName="
            + modelName + "&processorSpeed=" + processorSpeed + "&screenSize=" + screenSize;

    var myAjax = new Ajax.Request('createModelAction.do',
    {method:'get',
        parameters: postString,
        onFailure: function(t) {
            alert('Error: ' + t.status + '--' + t.statusText);
        }});

    return false;

}

function addItemPopupNewModel(title) {

    Modalbox.show('itemModelAction.do?method=viewCreateModelPopup', {title: title,
        width: 600,
        afterLoad: setAddItemPopupObservers,
        onHide: removeAddItemPopupObservers});
}

function setAddItemPopupObservers() {

    $('createModel').observe('click', Modalbox.hide);
}

function removeAddItemPopupObservers() {

    $('createModel').stopObserving('click', Modalbox.hide);
}

function populateUpdateInventoryDateForm() {

    var selectValue = document.getElementById('serial').value;

    var myAjax = new Ajax.Request('getEquipmentItemById.do?id=' + selectValue,
    {Accept: 'application/json',
        onSuccess: function(t) {

            var json = t.responseText.evalJSON(true);
            var newRow = Builder.node('tr');
            //alert(newRow);
            //alert(json[0].serial);
            var serialElement = Builder.node('td', json[0].serial);
            var assignedElement = Builder.node('td', json[0].assignedTo);
            var updateElement = Builder.node('td');
            var updateInputNode = Builder.node('input');
            updateInputNode.setAttribute('name', 'inventoryDate');
            updateInputNode.setAttribute('id', 'inventoryDate');
            updateElement.appendChild(updateInputNode);

            //alert("1");
            var removeElement = Builder.node('td');
            var removeElementButton = Builder.node('button');
            removeElementButton.setAttribute('value', 'Remove');
            removeElement.appendChild(removeElementButton);
            // need to add a callback function here to remove the line

            newRow.appendChild(serialElement);
            newRow.appendChild(assignedElement);
            newRow.appendChild(updateElement);

            $('updateDateTable').appendChild(newRow);

        },
        onFailure: function(t) {
            alert('Error: ' + t.status + '--' + t.statusText);
        }
    }
            );

    myAjax = null;
}

function createRosPackageDataRow() {

    //removeChildNodes(document.getElementById('message'));
    clearStatusMessageBox();

    var serial = $F('search');

    var myAjax = new Ajax.Request('getItemBySerial.do', {
        Accept:'application/json',
        method:'get',
        parameters: 'search=' + serial,
        onSuccess: function(t) {
            if (t.responseText == '') {
                $('message').appendChild(Builder.node('p', 'Item not found'));
                return false;
            }

            var json = t.responseText.evalJSON(true);
            var newRow = Builder.node('tr', {id: json.id + "-row"}, [
                    Builder.node('td', json.name),
                    Builder.node('td', json.manufacturerName),
                    Builder.node('td', json.description),
                    Builder.node('td', [
                            Builder.node('input', {type:'button', value:'Remove',
                                onclick:"javascript: Element.remove(document.getElementById('" + json.id + "-row')); return null;"}),
                            Builder.node('input', {type: 'hidden', value: json.id, id: json.id, name: 'pkgItemId'})
                            ])
                    ]
                    );
            $('rosPackageItems').appendChild(newRow);
        },
        onFailure: function(t) {
            $('message').appendChild(Builder.node('p', 'Error: ' + t.statusText));
        }
    });

    myAjax = null;
}

function addDrmoPackageItemBySerial() {

    removeChildNodes($('searchStatus'));

    var serial = $F('search');

    var myAjax = new Ajax.Request("getItemBySerial.do", {
        Accept:'application/json',
        method:'get',
        parameters: 'search=' + serial,
        onSuccess: function(t) {
            if (t.responseText == '') {
                $('searchStatus').appendChild(Builder.node('p', 'No items found'));
                return false;
            }

            var json = t.responseText.evalJSON(true);
            var newRow = Builder.node('tr', {id: json.id + "-row"}, [
                    Builder.node('td', json.name),
                    Builder.node('td', json.manufacturerName),
                    Builder.node('td', json.description),
                    Builder.node('td', [
                            Builder.node('input', {type:'button',value:'Remove',
                                onclick:"javascript: Element.remove(document.getElementById('" + json.id + "-row')); return null;"}),
                            Builder.node('input', {type: 'hidden', value: json.id, id: json.id, name: 'pkgItemId'})
                            ])
                    ]

                    );

            $('content').appendChild(newRow);
        }
        , onFailure: function(t) {
        alert('Error: ' + t.status + '--' + t.statusText);
    }
    }
            );

    myAjax = null;

}

function addDrmoPackageItem() {

    var itemId = $('itemId').value;

    var myAjax = new Ajax.Request('getEquipmentItemById.do', {
        Accept: 'application/json',
        method: 'get',
        parameters: 'id=' + itemId,
        onSuccess: function(t) {
            var json = t.responseText.evalJSON(true);
            var jsonObject = json[0];
            //var jsonLength = json.length;
            // TODO: Need an id for the tr so we can safely remove it
            var newRow = Builder.node('tr', {id: json.id + "-row"}, [
                    Builder.node('td', json.serial),
                    Builder.node('td', json.description),
                    Builder.node('td', [
                            Builder.node('input', {type:'button',value:'Remove',
                                onclick:"javascript: Element.remove(document.getElementById('" + json.id + "-row')); return null;"}),
                            Builder.node('input', {type: 'hidden', value: json.id, id: json.id, name: 'pkgItemId'})
                            ])
                    ]

                    );

            $('content').appendChild(newRow);

            // Remove that item from the dropdown list for convenience
            var itemIdOptions = itemId.options;
            for (var i = 0; i < itemIdOptions.length; i++) {
                if (itemIdOption[i].text == json.serial) {
                    itemIdOption[i] = null;
                    i = itemIdOptions.length;
                }
            }
        },
        onFailure: function(t) {
            alert('Error: ' + t.status + '--' + t.statusText);
        }
    });
}

function removeChildNodes(ctrl)
{
    alert(ctrl);

    while (ctrl.childNodes[0])
    {
        ctrl.removeChild(ctrl.childNodes[0]);
    }
}

function clearStatusMessageBox() {

    var statusBox = document.getElementById('message');

    while (statusBox.childNodes[0]) {
        statusBox.removeChild(statusBox.childNodes[0]);
    }
}

function confirmChangeDrmoItemConditionType() {

    //alert("Items: " + countIdentifiedDrmoEquipmentItems());
    if (countIdentifiedDrmoEquipmentItems() > 1) {

        if (confirm("Are you sure you wish to change the item condition? (All current packages will be removed!)")) {
            removeChildNodes($('content'));
        }
    } else {
        removeChildNodes($('content'));
    }

}

function confirmChangeDrmoItemType() {
    if (countIdentifiedDrmoEquipmentItems() > 1) {
        if (confirm("Are you sure you wish to change the Item Type? ALL CURRENT IDENTIFIED ITEMS WILL BE DELETED!")) {
            removeChildNodes($('content'));
            chainSelect('itemTypeId', 'manufacturerId', 'getManufacturerByEquipmentTypeAction.do');
        }
    } else {
        chainSelect('itemTypeId', 'manufacturerId', 'getManufacturerByEquipmentTypeAction.do');
    }
}

function countIdentifiedDrmoEquipmentItems() {

    var content = $('content');
    return content.childNodes.length;

}

function removeRow(id) {
    var table = $('itemTable');
    var tableChildren = table.childNodes;
}
// Utility

// Generic Chain Select function
// The following assumptions are made:
// - None of the function arguments are null
// - Any values in the select box that are "information-only" must have a value of < 0
// - The action returns a valid JSON object with values for "id" and "name" (aka description)
function chainSelect(originalId, destinationId, action) {

    if (originalId == null || destinationId == null || action == null) {
        return false;
    }

    var msie = false;
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        msie = true;
    }

    var origSelect = document.getElementById(originalId);
    //var origSelect = $(originalId);

    var destSelect = document.getElementById(destinationId);
    //var destSelect = $(destinationId);

    if (origSelect != null && destSelect != null) {

        var origSelectValue = origSelect.value;
        //var origSelectValue = $F(origSelect);
        var params = "id=" + origSelectValue;

        // I always have my "please select a value" label as -1
        if (origSelectValue > -1) {

            // Clean out the old values of the destination select box
            destSelect.options.length = 0;

            // Put the information-only option in
            // (the createElement is a stupid hack required by IE... stupid effing Microsoft)

            if (msie) {
                var myOpt = document.createElement('option');
                myOpt.text = '-- Loading --';
                myOpt.value = -1;
                destSelect.add(myOpt);
            } else {
                destSelect.appendChild(new Option('-- Loading --', -1));
            }
            //destSelect.add(myOpt, destSelect.selectedIndex);

            var myAjax = new Ajax.Request(action, {
                method: 'get',
                Accept: 'application/json',
                parameters: params,
                onSuccess: function(transport) {
                    var json = transport.responseText.evalJSON(true);
                    var jsonLength = json.length;

                    // Don't mess with the destination options unless there is data to put in
                    if (jsonLength > 0) {
                        destSelect.options.length = 0;

                        if (msie) {
                            var myOpt1 = document.createElement('option');
                            myOpt1.text = '-- Select --';
                            myOpt1.value = -1;
                            destSelect.add(myOpt1);
                        } else {
                            destSelect.appendChild(new Option('-- Select --', -1));
                        }

                        for (var i = 0; i < jsonLength; i++) {

                            if (msie) {
                                var tempOpt = document.createElement('option');
                                tempOpt.text = json[i].name;
                                tempOpt.value = json[i].id;
                                destSelect.add(tempOpt);
                            } else {
                                destSelect.appendChild(new Option(json[i].name, json[i].id));
                            }

                        }
                    }
                },
                onFailure: function(t) {
                    alert('Error: ' + t.status + '--' + t.statusText);
                }
            });

            myAjax = null;
        }

    }

    return false;

}

function multiChainSelect(arguments) {

    var length = multiChainSelect.arguments.length;

    // At minimum, the action and two boxes must be specified. The destination box must be first!
    if (length < 3) {
        return false;
    }

    var args = multiChainSelect.arguments;

    // Get the action and ensure that its a struts action ending in .do
    var action = args[0];
    if (action.indexOf(".do") == -1) {
        return false;
    }

    // Get the destination box
    var destSelect = document.getElementById(args[1]);
    //$(args[1]);

    // Build the parameters to pass to the action
    var params = '';
    for (var i = 2; i < args.length; i++) {
        params = params + args[i] + "=";
        params = params + $F(args[i]);
        if (i != args.length - 1) {
            params = params + "&";
        }
        //params.concat(multiChainSelect.arguments[i].concat('=').concat($F(multiChainSelect.arguments[i])));
    }

    // Ensure that we haven't passed a holder value in any of the parameters
    if (params.indexOf("-1") != -1) {
        return false;
    }

    // Start building the new select box
    destSelect.options.length = 0;
    destSelect.appendChild(new Option('-- Loading --', -1));

    var myAjax = new Ajax.Request(action, {
        method: 'get',
        Accept: 'application/json',
        parameters: params,
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON(true);
            var jsonLength = json.length;

            // Don't mess with the destination options unless there is data to put in
            if (jsonLength > 0) {
                destSelect.options.length = 0;
                destSelect.appendChild(new Option('-- Select --', -1));
                for (var i = 0; i < jsonLength; i++) {
                    destSelect.appendChild(new Option(json[i].name, json[i].id));
                }
            }
        },
        onFailure: function(t) {
            alert('Error: ' + t.status + '--' + t.statusText);
        }
    }
            );
    myAjax = null;

    return false;

}


// Pass in the id and an array of <td> objects
function createRow(rowid, cells) {

    var row = Builder.node('tr', {id: rowid}, cells);
    return row;

}

// Do NOT give these cells an ID, it will be replaced in createRow. Instead, pass in the elements inside the cell
function createCell() {

    var cell = Builder.node('td', arguments);
    return cell;
}

function createDataEntryRow() {

    if (loaded) {
        var table = document.getElementById('equipmentItemTable');
        var newRow = table.tBodies[0].rows[0].cloneNode(true);
        var selectBoxes = newRow.getElementsByTagName('select');
        for (var i = 0; i < selectBoxes.length; i++) {
            selectBoxes[i].value = -1;
        }
        var textBoxes = newRow.getElementsByTagName('input');
        for (var i = 0; i < textBoxes.length; i++) {
            textBoxes[i].value = '';
        }

        var newRowId = table.tBodies[0].rows.length;
        newRow.id = newRowId;
        table.tBodies[0].appendChild(newRow);
    }

    // Copy the first row


    // Reset the select boxen



    // Clear the input boxen



    // Set the id for the new row



    // Append the new row

}

function deleteDataEntryRow(obj) {

    if (loaded) {
        // Never delete the first data entry row!
        if (table.tBodies[0].rows.length < 2) {
            return null;
        }

        // Button/Link->TD->TR
        var deleteRow = obj.parentNode.parentNode;

        // TR->TBody
        var tBody = deleteRow.parentNode;

        // TBody->Table
        var tbl = deleteRow.parentNode;

        var deleteRowId = deleteRow.sectionRowIndex;

        tBody.deleteRow(deleteRowId);
    }
}

function validateRow(obj) {

    if (loaded) {
        var duplicates = false;
        var row = obj.parentNode.parentNode;
        var manufacturerId = row.cells[0].getElementsByTagName('select')[0].value;
        //var manufacturerId = row.cells[0].childNodes[0].value;
        var serial = row.cells[2].getElementsByTagName('input')[0].value;

        if ((manufacturerId == -1) && serial.length < 1) {
            alert('You must provide a manufacturer and serial number!');
            return false;
        }
        //var serial = row.cells[2].childNodes[0].value;
        var url = 'checkDuplicates.do?manufacturerId=' + manufacturerId + '&serial=' + serial;
        var myAjax = new Ajax.Request('checkDuplicates.do?manufacturerId=' + manufacturerId + '&serial=' + serial, {
            method:'get',
            Accept:'text/plain',
            onSuccess:function(t) {
                var txt = t.responseText;
                txt = txt.substring(0, 4);
                // get 1st 4 characters
                if (txt.toUpperCase() == 'TRUE') {
                    duplicates = true;
                    alert('ERROR: Duplicate item exists!');
                } else {
                    createDataEntryRow();
                }
            },
            onFailure:function(t) {
                alert('Error: ' + t.status + '--' + t.statusText);
            }
        });
        myAjax = null;
        return !duplicates;
        // if it's not duplicated, the row validates.
    }
}

function addNewRow(obj) {

    if (loaded) {
        if (validateRow(obj) == false) {
            createDataEntryRow();
        } else {
            // Need an error message
            alert('Cannot add item: duplicate item exists.');
        }
    }
}

function createDynamicSelector(elementName, home, valuesUrl) {

    // Check for XSS in values URL

    var form = Builder.node('form');
    var selector = Builder.node('select', {name:elementName, id:elementName});
    var submittor = Builder.node('input', {type:'submit', value:'Save', onclick:''});
    var cancellor = Builder.node('input', {type:'cancel', value:'Cancel', onclick:''});

    var myAjax = new Ajax.Request(valuesUrl, {
        method:'post',
        Accept:'application/json',
        onSuccess: function(t) {
            var jsonArray = t.responseText.evalJSON(true);
            var length = jsonArray.length;
            for (var i = 0; i < length; i++) {
                var opt = new Option(jsonArray[i].name, jsonArray[i].id);
                selector.appendChild(opt);
            }

        },
        onFailure: function(t) {
            alert('Error: ' + t.status + '--' + t.statusText);
        }
    });

    myAjax = null;

    form.appendChild(selector);
    form.appendChild(submittor);
    form.appendChild(cancellor);

    $(home).innerHTML = '';
    $(home).appendChild(form);
}

function removeAdpeAccountRow(rowId, acctId) {

    if (confirm("Are you sure you wish to remove this Account from the ADPE Account?")) {
        var myAjax = new Ajax.Request('accounts/removeAdpeAccount.do?adpeAccountId=' + rowId + "&accountId=" + acctId, {
            method: 'get',
            Accept: 'application/json',
            onSuccess: function(t) {
                var tBody = document.getElementById(rowId).parentNode;
                alert(tBody);
                alert($(rowId));
                tBody.deleteRow(document.getElementById(rowId));
            },
            onFailure: function(t) {
                alert('Error: ' + t.status + '--' + t.statusText);
            }
        });
    }
}

function createAccountDataTable() {
    alert("test");
    // YAHOO.usermgmt.XHR_JSON = new function() {

    var columnHeadings = [
    {key: "name", label: "Account"},
    {key: "organization", label: "Organization"},
    {key: "itemCount", label: "Total Items"},
    {key: "accountValue", label: "Account Value"},
    {key: "Actions"}
            ];

    this.dataSource = new YAHOO.util.DataSource('getAccountsByUser.do');
    this.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    this.dataSource.connXhrMode = "queueRequests";
    this.dataSource.responseSchema = {
        resultsList: "ResultSet.Result",
        fields: ["name", "organization", "itemCount", "accountValue"]
    };

    this.myDataTable = new YAHOO.widget.DataTable("json", columnHeadings, this.dataSource);

    var callback = {
        success: this.myDataTable.onDataReturnAppendRows(),
        failure: this.myDataTable.onDataReturnAppendRows(),
        scope: this.myDataTable
    };

    this.myDataSource.sendRequest(null, callback);
    //}

}

function handleCalendarSelect(type, args, obj) {

    var allDates = args[0];
    var singleDate = dates[0];

    var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];

    var year = date[0];
    var month = date[1];
    var day = date[2];

    var formattedDate = day + '-' + months[month] + '-' + year;

    document.getElementById(obj.id).value = formattedDate;

}